package com.lt.bcra.exception;


import com.lt.bcra.result.ResponseEnum;
import com.lt.bcra.result.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@Component //Spring容易自动管理
@RestControllerAdvice //在controller层添加通知。如果使用@ControllerAdvice，则方法上需要添加@ResponseBody
public class UnifiedExceptionHandler {

    /**
     * 未定义异常
     */
    @ExceptionHandler(value = Exception.class) //当controller中抛出Exception，则捕获
    public ResultData handleException(Exception e) {
        log.error(e.getMessage(), e);
        ResultData resultData = new ResultData();
        resultData.setStatus(ResponseEnum.ERROR);
        return resultData;
    }

    /**
     * 捕获自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = BaseException.class)
    public ResultData handleException(BaseException e) {
        log.error(e.getMessage(), e);
        ResultData resultData = new ResultData();
        resultData.setCode(e.getCode());
        resultData.setMessage(e.getMessage());
        return resultData;
    }


}
